package com.ptmall.app.alipay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.xfly.app.wxapi.PayResultListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * Created by Administrator on 2017/4/6.
 */

public class AliPay {

    //这个值必须要跟获取支付方式规则接口的一致，否则可能会无法判断支付方式
    public static final String WAY_ALIPAY = "ZhiFuBaoApp";

    //旧版支付标示位
    private static final int SDK_PAY_FLAG_V1 = 1;

    //新版支付标示位
    private static final int SDK_PAY_FLAG_V2 = 2;

    private static final int SDK_PAY_V1 = 1;
    private static final int SDK_PAY_V2 = 2;

    private Activity mActivity;
    private PayResultListener mPayResultListener;

    private AliPay(Activity activity, PayResultListener listener){
        this.mActivity = activity;
        this.mPayResultListener = listener;
    }

    public static AliPay createInstance(Activity activity, PayResultListener payResultListener){
        return new AliPay(activity, payResultListener);
    }

    /**
     * 支付宝支付
     *
     */
    public void pay(String payParams){
//        if (payParams.version == SDK_PAY_V1) {//旧版
            payV1(payParams);
//        } else if (payParams.version == SDK_PAY_V2) {//新版
//            payV2(payParams.orderInfo);
//        } else {
//            mPayResultListener.onFail("支付失败");
//        }
    }

    /**
     * 旧版支付
     */
    private void payV1(String orderInfo){
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                String result = alipay.pay(orderInfo,true);
                //同步的支付结果
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG_V1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 新版支付
     * @param orderInfo
     */
    private void payV2(String orderInfo){
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                //同步的支付结果
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG_V2;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public JSONObject string2JSON(String str, String split) {
        JSONObject json = new JSONObject();
        try {
            String[] arrStr = str.split(split);
            for (int i = 0; i < arrStr.length; i++) {
                String[] arrKeyValue = arrStr[i].split("=");
                json.put(arrKeyValue[0], arrStr[i].substring(arrKeyValue[0].length() + 1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    String getSuccess(JSONObject jsonObject) {
        String success = null;
        try {
            String result = jsonObject.getString("result");
            result = result.substring(1, result.length() - 1);
            JSONObject objResult = string2JSON(result, "&");
            success = objResult.getString("success");
            success = success.replace("\"", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success;
    }



    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG_V1:
                    /**
                     * strRet=resultStatus={9000};memo={};result={_input_charset=UTF-8&body=支付号20170406204049216476&notify_id=RqPnCoPT3K9%2Fvwbh3InYyPjMUURzUXj2eAyAfoPX1WXYd24IWNcSCcvfIzV3w8%2FHyvnF&notify_time=2017-04-06 20:41:08&notify_type=trade_status_sync&notify_url=http://shangcheng.xsy.dsceshi.cn/notify.php&out_trade_no=20170406204049216476&partner=2088711945621741&payment_type=1&seller_id=0561@9885.net&service=mobile.securitypay.pay&sign=JoeyZSIEC0vkFFlzvx5BjJNhZzWKwd1kYQmSxkeIpQsFgwUG2x2HaQC/lCI57RsSp93jLAOMXBDkxjssvAPRJ9x/EMr/rKAywFHYzgDVbiN50HKLz0+84DPTyjT06srgGHThVX59xBqM/Z6yKPHmpq8vLY7sRbbeKDpZCnlV0aU=&sign_type=RSA&spbill_create_ip=122.6.144.114&subject=支付号20170406204049216476&success=true&total_fee=0.01&trade_no=2017040621001004880291190905&trade_status=TRADE_SUCCESS}
                     */
                    String strRet = (String) msg.obj;
                    //执行校验，校验通过后则 判断code
                    Log.d("xucc","strRet="+strRet);
                    JSONObject result = string2JSON(strRet,";");
                    try {
                        String code = result.getString("resultStatus");
                        int resultCode = Integer.valueOf(code.substring(1, code.length() - 1));
                        if (resultCode == 9000) {//成功
                            String success = getSuccess(result);
                            if("true".equalsIgnoreCase(success)){
                                mPayResultListener.onSuccess(null);
                            } else {
                                mPayResultListener.onFail(success);
                            }
                        } else {
                            mPayResultListener.onFail(code);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mPayResultListener.onFail(strRet);
                    }
                    break;
                case SDK_PAY_FLAG_V2: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    Log.d("xuccAlipay", "resultInfo="+resultInfo);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //Toast.makeText(PayDemoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        mPayResultListener.onSuccess(payResult.getMemo());
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //Toast.makeText(PayDemoActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        mPayResultListener.onFail(payResult.getMemo());
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    /**
     * 新版支付结果类
     */
    private static class PayResult {
        private String resultStatus;
        private String result;
        private String memo;

        public PayResult(Map<String, String> rawResult) {
            if (rawResult == null) {
                return;
            }

            for (String key : rawResult.keySet()) {
                if (TextUtils.equals(key, "resultStatus")) {
                    resultStatus = rawResult.get(key);
                } else if (TextUtils.equals(key, "result")) {
                    result = rawResult.get(key);
                } else if (TextUtils.equals(key, "memo")) {
                    memo = rawResult.get(key);
                }
            }
        }

        @Override
        public String toString() {
            return "resultStatus={" + resultStatus + "};memo={" + memo
                    + "};result={" + result + "}";
        }

        /**
         * @return the resultStatus
         */
        public String getResultStatus() {
            return resultStatus;
        }

        /**
         * @return the memo
         */
        public String getMemo() {
            return memo;
        }

        /**
         * @return the result
         */
        public String getResult() {
            return result;
        }
    }




}
